import React, { Component } from 'react';

/**
 * 学习目标：组件通讯，父传子练习
 */

export default class Parent extends Component {
  state = {
    money: 1000,
  };

  handleMakeMoney = () => {
    this.setState({
      money: 1000 + this.state.money,
    });
  };

  // 1、父组件先声明函数
  handelCost = (nmb) => {
    const { money } = this.state;
    console.log(nmb);
    // 4、执行逻辑
    this.setState({ money: money - nmb });
  };

  render() {
    // cs快捷键
    const { money } = this.state;
    return (
      <div>
        <button onClick={this.handleMakeMoney}>爸爸开始赚钱了</button>
        {/* 2、父组件传递一个回调参数 */}
        <Child money={money} handelCost={this.handelCost}></Child>
      </div>
    );
  }
}

class Child extends React.Component {
  render() {
    // cp快捷键
    const { money, handelCost } = this.props;
    return (
      <div>
        <h1>家庭存款：{money} </h1>
        {/* 3、子组件调用回调参数，可以先传参数 */}
        <button
          onClick={() => {
            handelCost(2000);
          }}
        >
          花钱如流水
        </button>
      </div>
    );
  }
}
